<template>
  <div>
    <!-- 价格组参照关系设置 -->
    <basic-dialog
      width="60%"
      :title="referSetting.dialogTitle"
      :visible="referSetting.visible"
      :handleClose="handleReferSettingCancel"
    >
      <basic-table
        :showPagination="false"
        :showSelectCol="false"
        :loading="referSetting.tableInfo.loading"
        :columns="referSetting.tableInfo.columns"
        :dataSource="referSetting.tableInfo.list"
        :tableHeight="480"
      >
        <el-row type="flex" slot="content_context">
          <el-button type="primary" @click="handleSetPriceGroup">价格组设置</el-button>
        </el-row>
      </basic-table>
      <el-row slot="ft" type="flex" justify="center">
        <el-button @click="handleReferSettingCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="referSetting.submitBtnLoading"
          @click="handleReferSettingOk"
        >提交</el-button>
      </el-row>
    </basic-dialog>
    <!-- 价格组设置 -->
    <basic-dialog
      width="60%"
      :title="groupSetting.dialogTitle"
      :visible="groupSetting.visible"
      :handleClose="handleGroupSettingCancel"
    >
      <basic-table
        :showPagination="false"
        :showSelectCol="false"
        :loading="groupSetting.tableInfo.loading"
        :columns="groupSetting.tableInfo.columns"
        :dataSource="groupSetting.tableInfo.list"
        :tableHeight="480"
      >
        <el-row type="flex" slot="content_context">
          <el-button type="primary" @click="handleEachGroup">各省成组</el-button>
        </el-row>
      </basic-table>
      <el-row slot="ft" type="flex" justify="center">
        <el-button @click="handleGroupSettingCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="groupSetting.submitBtnLoading"
          @click="handleGroupSettingOk"
        >确定</el-button>
      </el-row>
    </basic-dialog>
  </div>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BasicTable from '@/components/BasicTable';
import GroupInfo from './GroupInfo';
import {
  getDefaultReferRelativeColumns,
  getDefaultGroupColumns,
  reloadRowByMainCityState,
  checkSetGroupDataIsChanged,
  getInitedListByGroupSetReferRelative,
  getNewListByEachGroup
} from './utils';
import { generateUuid } from '@/utils/bizUtils';
import { getCityNamesByPriceIneligibleRatio } from '@/utils/getUtils';
import { SALE_PAGE_NAMES, GROUP_SETTING_API, REFER_SETTING_API } from './constants';
import { echoSaleGroupAreaService, echoSaleGroupService } from '@/api/finance/common/salePrice';
export default {
  components: {
    BasicDialog,
    BasicTable
  },
  props: {
    coverReferRelativeColumns: {
      type: Function
    },
    visible: {
      type: Boolean,
      default: false
    },
    groupVisible: {
      type: Boolean,
      default: false
    },
    productUuids: {
      type: Array,
      default: () => []
    },
    pageName: {
      type: Symbol
    }
  },
  data () {
    return {
      // 价格组参照关系设置
      referSetting: new GroupInfo({
        dialogTitle: '价格组参照关系设置',
        columns: this.getReferRelativeColumns()
      }),
      // 价格组设置
      groupSetting: new GroupInfo({
        dialogTitle: '价格组设置',
        columns: this.getGroupColumns()
      }),
      referGroupOptions: [], // 参照组列下拉options
      originalGroupList: [], // 价格组设置表格数据原始数据（用来判断最终提交时是否有修改数据）
      submitUuid: '', // 价格组设置提交所需uuid
    }
  },
  computed: {
    // 只有一个productUuid
    isSingleUuid () {
      return this.productUuids.length === 1;
    },
    isEditGroupPage () {
      return this.pageName === SALE_PAGE_NAMES.EDIT_GROUP;
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.referSetting.changeVisible(val);
      }
    },
    groupVisible (val) {
      if (val) {
        this.groupSetting.changeVisible(val);
        this.getGroupList();
      }
    },
  },
  methods: {
    // jsx-render渲染价格比例数值输入框
    renderInputNumber (h, row, key) {
      return <el-input-number
        v-model={row[key]}
        placeholder="请输入..."
        disabled={row.uuid === row.mainGroupUuid}
        precision={2}
        controls={false}
      ></el-input-number>
    },
    // jsx-render渲染参照组下拉
    renderSelect (h, row, key, index) {
      return <el-select
        v-model={row[key]}
        placeholder="请选择"
        onChange={ val => { this.handleSelectReferGroup({ val, row, index }) } }
      >
        {
          this.referGroupOptions.map(item =>
            <el-option
              key={item.uuid}
              label={item.groupName}
              value={item.uuid}
            />
          )
        }
      </el-select>
    },
    // jsx-render渲染设置组输入框
    renderInput (h, row, key) {
      return <el-input
        v-model={row[key]}
        placeholder="请输入..."
      />
    },
    // jsx-render渲染是否主省radio组
    renderRadio (h, row, key, index) {
      const isDisabledMainCity = row.canSetMain == 2;
      return <el-radio-group
        v-model={row[key]}
        onChange={ val => this.handleSelectIsMainCity({ val, row, index }) }
      >
        <el-radio label="1" disabled={isDisabledMainCity}>是</el-radio>
        <el-radio label="2" disabled={isDisabledMainCity}>否</el-radio>
      </el-radio-group>
    },
    // 获取价格组参照关系表格表列
    getReferRelativeColumns () {
      const METHODS = {
        renderInputNumber: this.renderInputNumber,
        renderSelect: this.renderSelect
      }
      if (this.coverReferRelativeColumns) {
        return this.coverReferRelativeColumns(METHODS);
      }
      return getDefaultReferRelativeColumns(METHODS);
    },
    // 获取价格组表格表列
    getGroupColumns () {
      const METHODS = {
        renderInput: this.renderInput,
        renderRadio: this.renderRadio
      }
      if (this.coverGroupColumns) {
        return this.coverGroupColumns(METHODS);
      }
      return getDefaultGroupColumns(METHODS);
    },
    // 选择参照组
    handleSelectReferGroup ({ val, row, index }) {
      const isReferSelf = val === row.uuid; // 参照自己
      if (isReferSelf) {
        this.referSetting.setRowProp(index, 'rate', 1);
      } else {
        this.referSetting.setRowProp(index, 'rate', undefined);
      }
      const target = this.referGroupOptions.find(item => item.mainGroupUuid === val);
      if (target) {
        row.mainGroupUuid = target.mainGroupUuid;
        row.mainGroupName = target.mainGroupName;
      }
    },
    // 价格组设置
    handleSetPriceGroup () {
      this.groupSetting.changeVisible(true);
      if (!this.productUuids) {
        return this.$message.warning('没有productUuid，请确认商品信息是否完整');
      }
      this.getGroupList();
    },
    // 各省成组
    handleEachGroup () {
      const result = getNewListByEachGroup(this.groupSetting.getTableData());
      this.groupSetting.setTableData(result);
    },
    // 获取价格组设置查询api相关信息
    getGroupSettingSearchApi () {
      if (this.isEditGroupPage && this.isSingleUuid) { // 是修改价格组 - 单个productUuid要调用特殊接口
        return {
          method: echoSaleGroupAreaService,
          data: { productUuid: this.productUuids[0] }
        }
      }
      return {
        method: GROUP_SETTING_API[this.pageName].search,
        data: { productUuids: this.productUuids, areaType: 1 }
      }
    },
    // 获取价格组设置表格数据
    async getGroupList () {
      const { method, data } = this.getGroupSettingSearchApi();
      const retData = await method(
        data, state => { this.groupSetting.changeLoading(state); }
      );
      if (retData) {
        const tableData = retData.map(item => ({
          ...item, productUuids: this.productUuids.join(',')
        }));
        this.originalGroupList = _.cloneDeep(tableData); // 备份初始数据
        this.groupSetting.setTableData(tableData);
      }
    },
    // 关闭价格组设置弹框
    closeGroupSettingDialog () {
      this.groupSetting.changeVisible(false);
      this.$emit('update:groupVisible', false);
    },
    // 价格组设置确定
    async handleGroupSettingOk () {
      this.submitUuid = generateUuid(); // 每次价格组设置弹框提交表格数据时生成
      const submitMethod = GROUP_SETTING_API[this.pageName].submit;
      const params = {
        uuid: this.submitUuid,
        data: this.groupSetting.getTableData()
      }
      const retStatus = await submitMethod(
        params, state => { this.groupSetting.changeSubmitBtnLoading(state) }
      );
      if (retStatus) {
        this.referSetting.changeVisible(true);
        this.closeGroupSettingDialog();
        this.getReferRelativeGroupList();
      }
    },
    // 价格组设置取消
    handleGroupSettingCancel () {
      this.closeGroupSettingDialog();
    },
    // 选择是否主省
    handleSelectIsMainCity (data) {
      reloadRowByMainCityState(this.groupSetting, data);
    },
    // 获取价格组参照关系设置查询api相关信息
    getReferSettingSearchApi () {
      const presentGroupList = this.groupSetting.getTableData();
      const hasNoChangeGroupSet = !checkSetGroupDataIsChanged(this.originalGroupList, presentGroupList);
      const uuid = this.submitUuid;
      if (this.isEditGroupPage && this.isSingleUuid && hasNoChangeGroupSet) {
        return {
          method: echoSaleGroupService,
          data: { uuid, productUuid: this.productUuids[0] }
        }
      }
      return {
        method: REFER_SETTING_API[this.pageName].search,
        data: { uuid, productUuid: this.productUuids }
      }
    },
    // 获取价格组参照关系设置表格数据
    async getReferRelativeGroupList () {
      const { method, data } = this.getReferSettingSearchApi();
      const retData = await method(
        data, state => { this.referSetting.changeLoading(state) }
      );
      if (retData) {
        const tableData = getInitedListByGroupSetReferRelative(retData);
        this.referSetting.setTableData(tableData);
        this.referGroupOptions = tableData.map(item => ({
          uuid: item.uuid, groupName: item.groupName
        }));
      }
    },
    // 获取价格组参照关系设置提交入参
    getSubmitGroupReferParams () {
      const isOnlySingleUuidPage =
        this.pageName === SALE_PAGE_NAMES.ADD ||
        this.pageName === SALE_PAGE_NAMES.ADD_WAITING;
      const data = { rowList: this.referSetting.getTableData() }
      if (isOnlySingleUuidPage) {
        data.productUuid = this.productUuids[0]
      } else {
        data.productUuids = this.productUuids
      }
      return {
        uuid: this.submitUuid,
        data
      }
    },
    // 关闭价格组参照关系设置弹框
    closeReferSettingDialog () {
      this.referSetting.changeVisible(false);
      this.$emit('update:visible', false);
    },
    // 提交价格组参照关系设置数据
    async handleReferSettingOk () {
      const warnMsgs = getCityNamesByPriceIneligibleRatio(this.referSetting.getTableData());
      if (warnMsgs) {
        return this.$message.warning(`${warnMsgs}：价格比例需在0.6-5之间`);
      }
      const data = this.getSubmitGroupReferParams();
      const submitMehod = REFER_SETTING_API[this.pageName].submit;
      const result = await submitMehod(
        data, state => { this.referSetting.changeSubmitBtnLoading(state) }
      );
      if (result) {
        this.$message.success('价格组参照关系提交成功');
        this.$emit('getSubmitReferGroupResult', { result, uuid: this.submitUuid });
        this.closeReferSettingDialog();
      }
    },
    // 价格组参照关系设置取消
    handleReferSettingCancel () {
      this.closeReferSettingDialog();
    }
  }
}
</script>
